﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
using CalcSharp.Core.IO;
using CalcSharp.Core.PackageMan;


namespace pkg2xml
{
    class Program
    {
        static void help()
        {
            Console.WriteLine("PKG2XML - An utility to create xml package list from package files");
            Console.WriteLine("Usage: pkg2xml -src <directory>");
            Console.WriteLine("   -src: The source directory");
        }

        static void Main(string[] args)
        {
            string src = null;
            try
            {
                for (int i = 0; i < args.Length; i++)
                {
                    if (args[i] == "-src") src = args[i + 1];
                }
                if (string.IsNullOrEmpty(src)) help();
                else
                {
                    string[] files = Directory.GetFiles(src, "*.cspack");
                    List<Package> pkglist = new List<Package>();
                    Package tmp;

                    foreach (string file in files)
                    {
                        tmp = ZipPack.getpackageinfo(file);
                        pkglist.Add(tmp);
                    }

                    XmlSerializer xs = new XmlSerializer(typeof(Package[]));
                    FileStream output = File.Create(src+@"\repository.xml.gz");
                    MemoryStream uncompressed = new MemoryStream();

                    xs.Serialize(uncompressed, pkglist.ToArray());

                    uncompressed.Seek(0, SeekOrigin.Begin); //seek to begining

                    StreamHelper.Compress(uncompressed, output, CompressFormat.gzip);

                    uncompressed.Close();
                    output.Close();

                    Console.WriteLine("Created repository.xml.gz file");
                }
            }
            catch
            {
                help();
            }
        }
    }
}
